import torch
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary

class DoubleConv(nn.Module):
    def __init__(self, in_channels, out_channels, dropout_rate=.0, kernel_size=(7, 1)):
        super().__init__()
        self.double_conv = nn.Sequential(
            # nn.BatchNorm2d(out_channels),
            nn.Conv2d(in_channels, out_channels, kernel_size, padding=(
                int(kernel_size[0]/2), int(kernel_size[1]/2))),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Dropout2d(p=dropout_rate),
            nn.Conv2d(out_channels, out_channels, kernel_size, padding=(
                int(kernel_size[0]/2), int(kernel_size[1]/2))),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Dropout2d(p=dropout_rate)
        )

    def forward(self, x):
        return self.double_conv(x)


class SingleConv(nn.Module):
    def __init__(self, in_channels, out_channels, dropout_rate=.0, kernel_size=(7, 1)):
        super().__init__()
        self.single_conv = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size, padding=(
                int(kernel_size[0]/2), int(kernel_size[1]/2))),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Dropout2d(p=dropout_rate)
        )

    def forward(self, x):
        return self.single_conv(x)


class FinalConv(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=(7, 1)):
        super().__init__()
        self.double_conv = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size, padding=(
                int(kernel_size[0]/2), int(kernel_size[1]/2))),
            nn.BatchNorm2d(out_channels),
            nn.Softmax(dim=1)
        )

    def forward(self, x):
        return self.double_conv(x)


class Down(nn.Module):
    def __init__(self, in_channels, out_channels, dropout_rate=.0, stride_size=(4, 1), kernel_size=(7, 1)):
        super().__init__()
        self.down_conv = nn.Sequential(
            # nn.MaxPool2d((7,1)),
            nn.Conv2d(in_channels, in_channels, kernel_size=kernel_size, stride=stride_size, padding=(
                int(kernel_size[0]/2), int(kernel_size[1]/2))),
            nn.ReLU(inplace=True),
            nn.Dropout2d(p=dropout_rate),
            nn.Conv2d(in_channels, out_channels, kernel_size, padding=(
                int(kernel_size[0]/2), int(kernel_size[1]/2))),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Dropout2d(p=dropout_rate)
        )

    def forward(self, x):
        return self.down_conv(x)


class Up(nn.Module):
    def __init__(self, in_channels, out_channels, dropout_rate=.0, stride_size=(4, 1), kernel_size=(7, 1)):
        super().__init__()
        self.up = nn.Sequential(nn.ConvTranspose2d(
            in_channels, out_channels, kernel_size=kernel_size, stride=stride_size),
            nn.ReLU(),
            nn.Dropout2d(p=dropout_rate)
        )
        self.conv = nn.Sequential(
            nn.Conv2d(2*out_channels, out_channels, kernel_size, padding=(
                int(kernel_size[0]/2), int(kernel_size[1]/2))),
            nn.BatchNorm2d(out_channels),
            nn.ReLU(inplace=True),
            nn.Dropout2d(p=dropout_rate)
        )

    def forward(self, x1, x2):
        x1 = self.up(x1)

        # 填充0，使得x1、x2尺寸相同
        dy = (x2.size()[2] - x1.size()[2])
        dx = (x2.size()[3] - x1.size()[3])
        x1 = F.pad(x1, [int(dx/2), dx-int(dx/2), int(dy/2), dy-int(dy/2)])

        x = torch.cat([x2, x1], dim=1)
        return self.conv(x)


class Model(nn.Module):
    def __init__(self, dropout_rate=.0):
        super().__init__()
        print("initializing unet")
        self.n_channels = 3
        self.n_classes = 3
        # 定义每一个层
        self.inc = DoubleConv(self.n_channels, 8, dropout_rate=dropout_rate)
        self.down1 = Down(8, 16, dropout_rate=dropout_rate)
        self.down2 = Down(16, 22, dropout_rate=dropout_rate)
        self.down3 = Down(22, 32, dropout_rate=dropout_rate)
        self.down4 = Down(32, 64, dropout_rate=dropout_rate)
        self.up1 = Up(64, 32, dropout_rate=dropout_rate)
        self.up2 = Up(32, 22, dropout_rate=dropout_rate)
        self.up3 = Up(22, 16, dropout_rate=dropout_rate)
        self.up4 = Up(16, 8, dropout_rate=dropout_rate)
        self.outc = FinalConv(8, self.n_classes)

    def forward(self, x):
        # 正向传播过程：数据经过每个层，得到输出
        x = x.unsqueeze(3)
        # print(x.shape)
        x1 = self.inc(x)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        logits = self.outc(x)
        logits = logits.squeeze(dim=3)
        return logits


if __name__ == "__main__":
    model = Model()
    summary(model,(3,4096),device='cpu')
    x = torch.randn([10, 3, 6144])
    y = model(x)
    print(y.shape)